//
//  RegexUtil.swift
//  Utility
//
//  Created by 于虎拴 on 2022/12/1.
//

import Foundation

public enum Pattern: String, CaseIterable, CustomStringConvertible {
  case account = "^[a-zA-Z0-9_-]{3,20}$"
  case allSymbols = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]"
  case commonSymbols = "^[\\da-zA-z!#$%^&*]$"
  
  public var description: String {
    switch self {
    case .account:
      return "大小写字母、数字、下划线、3-20个字符"
    case .allSymbols:
      return "匹配所有特殊字符"
    case .commonSymbols:
      return "匹配常见特殊字符"
    }
  }
}


public struct RegexHelper {
  let regex: NSRegularExpression?
  
  init(_ pattern: String) {
    self.regex = try? NSRegularExpression(pattern: pattern)
  }
  
  func match(input: String) -> Bool {
    if let matchs = regex?.matches(in: input, range: NSRange(location: .zero, length: input.count)) {
      return !matchs.isEmpty
    } else {
      return false
    }
  }
}

extension String {
  public func match(_ input: String) -> Bool {
    return RegexHelper(self).match(input: input)
  }
}

precedencegroup RegexPrecedence {
  higherThan: MultiplicationPrecedence
  associativity: none
  assignment: false
}

infix operator =~ : RegexPrecedence

func =~(lhs: String, rhs: String) -> Bool {
  if lhs.first == "^" && lhs.last == "$" {
    return RegexHelper(lhs).match(input: rhs)
  } else {
    return RegexHelper(rhs).match(input: lhs)
  }
}
